﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using Hematology.Data;
using Hematology.Tools;
using Hematology.Tools.Text;
using Hematology.UserSite.Controls;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite.admin
{
	public partial class EditContent : NgoPage
	{

		#region Properties

		protected EnumHelper.ContentType CurrentContentType
		{
			get
			{
				return ViewState["CurrentContentType"] != null
						   ? (EnumHelper.ContentType)Enum.Parse(typeof(EnumHelper.ContentType), ViewState["CurrentContentType"].ToString())
						   : EnumHelper.ContentType.Community;
			}
			set { ViewState["CurrentContentType"] = value; }
		}

		private EnumHelper.PageSection CurrentPageSection
		{
			get
			{
				return ViewState["CurrentPageSection"] != null
						   ? (EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), ViewState["CurrentPageSection"].ToString())
						   : EnumHelper.PageSection.List;
			}
			set { ViewState["CurrentPageSection"] = value; }
		}

		private SiteContent CurrentSiteContent
		{
			get { return (SiteContent)ViewState["CurrentSiteContent"]; }
			set { ViewState["CurrentSiteContent"] = value; }
		}

		private string ListUrl
		{
			get { return String.Format("/admin/EditContent.aspx?ct={0}&view=List", CurrentContentType); }
		}

		#endregion

		#region Fill methods

		private void FillTitleLabel()
		{
			lblSiteContentTitle.Text = CurrentContentType == EnumHelper.ContentType.News
			                           	? NgoResource.resSiteContentTitleNews
			                           	: NgoResource.resSiteContentCaption;
		}

		private void FillEditForm()
		{
			FillTitleLabel();

			string sSiteContentId = Request.QueryString["id"];
			int iSiteContentId;
			if (!String.IsNullOrEmpty(sSiteContentId) && Int32.TryParse(sSiteContentId, out iSiteContentId))
			{
				SiteContent oSiteContent = SiteContent.Get(iSiteContentId);
				if (oSiteContent != null)
				{
					CurrentSiteContent = oSiteContent;
					FillFileAttachList(iSiteContentId);

					txtSiteContentTitle.Text = oSiteContent.Title;
					ckedSiteContent.Text = oSiteContent.Content;
					if (oSiteContent.IsVisible != null)
						checkIsVisible.Checked = oSiteContent.IsVisible.Value;
				}
			}

			FillParentContentList();
		}

		private void FillContentList()
		{
			List<SiteContent> lstSiteContent = SiteContent.ListAllContent((int)CurrentContentType, false, false);

			rptSiteContent.DataSource = lstSiteContent;
			rptSiteContent.DataBind();
		}

		private void FillPage()
		{
			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
				case EnumHelper.PageSection.Add:
					ToolbarSetup();
					FillEditForm();

					mvSiteContent.ActiveViewIndex = 1;

					break;
				default:
					FillContentList();

					mvSiteContent.ActiveViewIndex = 0;

					break;
			}
		}

		private void FillViewStateVariables()
		{
			string pageSection = Request.QueryString["view"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.PageSection)), pageSection) > -1)
			{
				CurrentPageSection =
					(EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), pageSection);
			}

			string contentType = Request.QueryString["ct"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.ContentType)), contentType) > -1)
			{
				CurrentContentType =
					(EnumHelper.ContentType)Enum.Parse(typeof(EnumHelper.ContentType), contentType);
				ptTitle.DataBind();
			}
		}

		private void FillFileAttachList(int siteContentId)
		{
			btnSaveAttach.Visible = true;

			List<FileAttach> listFileAttach = FileAttach.ListBySiteContentId(siteContentId);
			if (listFileAttach != null)
			{
				rptContentAttach.DataSource = listFileAttach;
				rptContentAttach.DataBind();
			}
		}

		private void FillParentContentList()
		{
			List<SiteContent> lSiteContent = SiteContent.ListAllContent((Int32)CurrentContentType, false, true);
			if (lSiteContent != null)
			{
				if (CurrentSiteContent != null)
					lSiteContent.RemoveAll(siteContent => siteContent.Equals(CurrentSiteContent));

				ddlParentSiteContent.DataSource = lSiteContent;
				ddlParentSiteContent.DataBind();
			}
			ddlParentSiteContent.Items.Insert(0, new ListItem(NgoResource.resParentFree, "-1"));

			if (CurrentSiteContent != null && CurrentSiteContent.ParentSiteContentId != null)
			{
				ddlParentSiteContent.SelectedValue = CurrentSiteContent.ParentSiteContentId.Value.ToString();
			}
		}

		#endregion

		#region Other methods

		private void ToolbarSetup()
		{
			ckedSiteContent.config.skin = "office2003";
			ckedSiteContent.config.toolbar = PageHelper.EditorButtonSet;

			ckedSiteContent.DisableObjectResizing = true;
			ckedSiteContent.ResizeEnabled = false;
			ckedSiteContent.Width = 904;
		}

		private void SaveAttach(int iSiteContentId)
		{
			if (String.IsNullOrEmpty(fuAttachFile.FileName))
				return;

			if (!fuAttachFile.HasFile || !FileValidate(fuAttachFile.PostedFile.ContentType))
				return;

			string sFullPath = Path.Combine(Server.MapPath(ConfigReader.SiteContentAttachmentPath), fuAttachFile.FileName);

			FileStream fsWriteAttachmentStream = new FileStream(sFullPath, FileMode.Create, FileAccess.ReadWrite);
			using (BinaryWriter binWriter = new BinaryWriter(fsWriteAttachmentStream))
			{
				binWriter.Write(FileHelper.ReadFileContent(fuAttachFile.PostedFile.InputStream));
				binWriter.Close();
			}

			if (!File.Exists(sFullPath))
				return;

			FileAttach emailTemplateAttach = new FileAttach
			{
				SiteContentId = iSiteContentId,
				DocumentName = fuAttachFile.FileName,
				DocumentType = fuAttachFile.PostedFile.ContentType,
				DocumentSize = fuAttachFile.PostedFile.ContentLength
			};

			emailTemplateAttach.Save();
			if (!emailTemplateAttach.AttachId.HasValue)
				return;

			FillFileAttachList(iSiteContentId);
		}

		protected bool FileValidate(string sContentType)
		{
			string[] sGrantedTypes = TextHelper.AllowedFileTypes;
			return Array.IndexOf(sGrantedTypes, sContentType) != -1;
		}

		private void SetTitle()
		{
			string sBaseTitleString = string.Format("{0} \"{1}\"", NgoResource.resPartManager,
													NgoResource.ResourceManager.GetString(
														string.Format("resTopic{0}", CurrentContentType.ToString())));

			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resEdit);
					break;
				case EnumHelper.PageSection.Add:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resNew);
					break;
				default:
					ptTitle.Text = string.Format("{0} - {1}", sBaseTitleString, NgoResource.resList);
					break;
			}
		}

		#endregion

		#region Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				FillViewStateVariables();
				FillPage();
			}

			SetTitle();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			if (!Page.IsValid)
				return;

			string sParentContentId = ddlParentSiteContent.SelectedValue;

			int iParentContentId;
			if (String.IsNullOrEmpty(sParentContentId) || !Int32.TryParse(sParentContentId, out iParentContentId))
				return;

			if (CurrentPageSection == EnumHelper.PageSection.Add)
			{
				SiteContent siteContent = new SiteContent
											{
												ParentSiteContentId = iParentContentId != -1 ? iParentContentId : (int?) null,
												Content = ckedSiteContent.Text,
												Title = txtSiteContentTitle.Text.Trim(),
												ContentTypeCode = (int)CurrentContentType,
												IsVisible = checkIsVisible.Checked
											};

				siteContent.Save();

				if (siteContent.SiteContentId != null)
				{
					SaveAttach(siteContent.SiteContentId.Value);

					if (cbCloseAfterSave.Checked)
						Response.Redirect(ListUrl);
				}
			}
			else
			{
				CurrentSiteContent.ParentSiteContentId = iParentContentId != -1 ? iParentContentId : (int?) null;
				CurrentSiteContent.Content = ckedSiteContent.Text;
				CurrentSiteContent.Title = txtSiteContentTitle.Text.Trim();
				CurrentSiteContent.ContentTypeCode = (int)CurrentContentType;
				CurrentSiteContent.CreateDate = CurrentSiteContent.CreateDate;
				CurrentSiteContent.IsVisible = checkIsVisible.Checked;

				CurrentSiteContent.UpdateInstance();

				if (cbCloseAfterSave.Checked)
					Response.Redirect(ListUrl);
			}
		}

		protected void btnList_Click(object sender, EventArgs e)
		{
			string sNewUrl = string.Format(ListUrl);
			Response.Redirect(sNewUrl);
		}

		protected void rptSiteContent_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteContent")
			{
				int siteContentId = Convert.ToInt32(e.CommandArgument);
				SiteContent siteContent = SiteContent.Get(siteContentId);
				siteContent.IsDeleted = true;

				siteContent.UpdateInstance();

				FillContentList();
			}

			//if (e.CommandName.Equals("DeleteSelected"))
			//{
			//    if (rptNews.Items.Count > 0)
			//    {
			//        List<int> listNewsIdForDelete = new List<int>();
			//        for (int count = 0; count < rptNews.Items.Count; count++)
			//        {
			//            CheckBox chk = (CheckBox)rptNews.Items[count].FindControl("chkForDelete");
			//            if (chk.Checked)
			//            {
			//                listNewsIdForDelete.Add(rptNews.Items[count].DataItem);
			//            }
			//        }
			//    }
			//}
		}

		protected void rptContentAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach fileAttach = FileAttach.Get(iAttachId);
				fileAttach.IsDeleted = true;

				fileAttach.UpdateInstance();

				if (CurrentSiteContent.SiteContentId != null)
				{
					FillFileAttachList(CurrentSiteContent.SiteContentId.Value);
				}
			}
			else if (e.CommandName == "OpenAttach")
			{
				int iAttachId = Convert.ToInt32(e.CommandArgument);
				FileAttach fileAttach = FileAttach.Get(iAttachId);
				if (fileAttach != null)
				{
					Response.Redirect(Path.Combine(ConfigReader.SiteContentAttachmentPath, fileAttach.DocumentName));
				}
			}
		}

		protected void btnSaveAttach_Click(object sender, EventArgs e)
		{
			if (CurrentSiteContent != null && CurrentSiteContent.SiteContentId.HasValue)
			{
				SaveAttach(CurrentSiteContent.SiteContentId.Value);
			}
		}

		#endregion
	}
}